import React, { useEffect, useState } from 'react'

// 路由，acios
import { withRouter } from 'react-router-dom'
import axios from 'axios';

// 样式
import './sidemenu.css'

// antd组件
import { Layout, Menu } from 'antd';
import {
  UserOutlined,
} from '@ant-design/icons';
const { Sider } = Layout;
const { SubMenu } = Menu

// 路由与图标的映射关系
const icon = {
  "/home": <UserOutlined />,
  "/user-manage": <UserOutlined />,
  "/right-manage": <UserOutlined />,
  "/news-manage": <UserOutlined />,
  "/audit-manage": <UserOutlined />,
  "/publish-manage": <UserOutlined />,
}



function SideMenu(props) {

  // menuList 侧边栏数据
  const [menuList, setMenuList] = useState([])

  // 从后端 获取侧边栏数据menuList
  useEffect(() => {
    axios.get("http://localhost:5000/rights?_embed=children").then((res) => {
      setMenuList(res.data)
    })
  }, [])


  // 循环渲染侧边MenuItem
  const renderMenuItem = (menuList) => {
    // 循环渲染menuItem
    return menuList.map((o) => {
      // 判断是否是可下拉Item(有child)
      // 如果有childen,渲染SubMenu
      if (o.children?.length > 0) {
        return (
          // 有o.pagepermisson权限的才显示
          o.pagepermisson === 1 &&
          <SubMenu key={o.key} icon={icon[o.key]} title={o.title}>
            {
              // 回调自身
              renderMenuItem(o.children)
            }
          </SubMenu>)
      }
      // 如果没有child,渲染Menu.Item
      else {
        return (
          // 有o.pagepermisson权限的才显示
          o.pagepermisson === 1 &&
          <Menu.Item key={o.key} icon={icon[o.key]} onClick={() => {
            // 根据key存放的路由值进行路由跳转
            props.history.push(o.key)
          }
          }>{o.title}</Menu.Item>)
      }
    })
  }

  // 高亮menu值
  // console.log(props.location.pathname)//url /right-manage/role/list
  const selectedKeys = [props.location.pathname]

  // menu展开项
  // console.log(props.location.pathname)//url /right-manage/role/list
  // console.log(props.location.pathname.split('/')) //['', 'right-manage', 'role', 'list']
  // console.log(props.location.pathname.split('/')[1])//right-manage
  const openKeys = ["/" + props.location.pathname.split('/')[1]]

  // 渲染
  return (
    <Sider>
      <div className="sider">
        <div className="logo">全球新闻发布系统</div>
        <div className="menu">
          {/* 选中的不要用default ,直接用selectedKeys 因为会动态变化*/}
          {/* 是否下拉要用default,即defaultOpenKeys 否则点不开其他下拉menu */}
          <Menu theme="dark" mode="inline" selectedKeys={selectedKeys} defaultOpenKeys={openKeys}>
            {
              // 循环渲染侧边栏标题MenuItem
              renderMenuItem(menuList)
            }
          </Menu>
        </div>
      </div>
    </Sider>
  )
}


export default withRouter(SideMenu)